package com.example.hxpc.guidancemanagement.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.hxpc.guidancemanagement.R;
import com.example.hxpc.guidancemanagement.api.BaseApi;
import com.example.hxpc.guidancemanagement.base.ActivityInfo;
import com.example.hxpc.guidancemanagement.base.Message;
import com.example.hxpc.guidancemanagement.base.ProjectInfo;
import com.example.hxpc.guidancemanagement.model.JsonBase;
import com.example.hxpc.guidancemanagement.model.JsonFeedback;
import com.example.hxpc.guidancemanagement.tools.LogoutT;
import com.example.hxpc.guidancemanagement.tools.SharePreferenceTools;
import com.example.hxpc.guidancemanagement.tools.ToastTools;
import com.example.hxpc.guidancemanagement.tools.dataTools.Judge;
import com.example.hxpc.guidancemanagement.tools.dataTools.OkHttpTools;
import com.example.hxpc.guidancemanagement.tools.mold.BasePopupWindow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.hxpc.guidancemanagement.R.id.gridView;

/**
 * Created by tao on 2017/12/4.
 */

public class MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.MyViewHolder>{
    private List<ProjectInfo> mDatas = null;
    private OnItemClickListener mOnItemClickListener = null;
    private RecyclerView mRecyclerView;
    private Context mContext;
    private List<ActivityInfo> aDatas = null;
    private int screenHeight;
    private int screenWidth;
    private PopupWindow popupWindow;
    private LayoutInflater inflater;
//    private List<Message> ls_content ;
    private Map<Integer,List> map = new HashMap<Integer,List>();

    private boolean lf = false;

    private OkHttpTools okHttpTools = new OkHttpTools();

    private boolean flg = false;//判断符

    private View VIEW_FOOTER;
    private View VIEW_HEADER;

    //type
    private int TYPE_NORMAL = 1000;
    private int TYPE_HEADER = 1001;
    private int TYPE_FOOTER = 1002;

//    @Override
//    public void onClick(View v) {
//        if (mOnItemClickListener != null){
//            //将position保存在itemView的Tag中以便点击时进行获取
//            mOnItemClickListener.OnItemClick(v, (Integer) v.getTag());
//            mOnItemClickListener.onItemLongOnClick(v, (Integer) v.getTag());
//        }
//    }

    //定义一个供点击的接口
    public static interface OnItemClickListener{
        void OnItemClick(View view , int position);
        void onItemLongOnClick(View view ,int position);
    }
    public MyRecycleViewAdapter(Context mContext,List<ProjectInfo> mDatas){
        this.mContext = mContext;
        this.mDatas = mDatas;
        inflater = LayoutInflater.from(mContext);
//        LogoutT.logout("00"+mDatas.size());
    }

    public MyRecycleViewAdapter(Context mContext,List<ActivityInfo> aDatas,boolean flg){
        this.mContext = mContext;
        this.aDatas = aDatas;
        this.flg = flg;
        inflater = LayoutInflater.from(mContext);
//        LogoutT.logout("00"+aDatas.size());
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.mOnItemClickListener = listener;
    }

    public void init(){
        if (aDatas.size()!=0){
            for (int i = 0;i<aDatas.size();i++){
                List<Message> ls_content = new ArrayList<>();
                map.put(i,ls_content);
                LogoutT.logout("939393   "+ map.size());
            }
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOTER){
            return  new MyViewHolder(VIEW_FOOTER);
        }else if (viewType == TYPE_HEADER){
            return new MyViewHolder(VIEW_HEADER);
        }else{
            if (flg == true){
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_recyclerview_item , parent,false);
//                view.setOnClickListener(this);
                return new MyViewHolder(view);
            }else {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycleview_item,parent,false);
//                view.setOnClickListener(this);
                return new MyViewHolder(view);
            }
        }
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        if (!isFooterView(position)&&!isHeaderView(position)){
            if (haveHeaderView())
                position--;
            if (flg == true){
//                LogoutT.logout("headphoto   "+aDatas.get(position).getAvatar());
//                holder.img.setImageResource(aDatas.get(position).getAvatar());
                LogoutT.logout(aDatas.size()+"  9999999");
                init();
                Glide.with(mContext)
                        .load(aDatas.get(position).getAvatar())
                        .error(R.mipmap.ic_launcher_round)
                        .override(180,180)
                        .into(holder.img);
                holder.te_publish_time.setText(aDatas.get(position).getPublishTime());
                holder.te_name.setText(aDatas.get(position).getName());
                holder.content.setText(aDatas.get(position).getContent());
//                if (aDatas.get(position).getListUrls()==null||aDatas.get(position).getListUrls().size()==0){
//                    holder.gridView.setVisibility(View.GONE);
//                    LogoutT.logout("gone  gone");
//                    LogoutT.logout(aDatas.get(position).getListUrls()+"  "+ aDatas.get(position).getListUrls().size());
//                }
//                LogoutT.logout("wwww   "+aDatas.size());
                holder.gridView.setAdapter(new GridAdapter(aDatas.get(position).getListUrls(),mContext));
                holder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        ToastTools.toastMsg(mContext,position+"");
//                        imageBrower(position,aDatas.get(position).getListUrls());
                    }
                });
                final int finalPosition = position;
//                Judge.getInstance().setNum(position);
//                LogoutT.logout(finalPosition + "6363");
                holder.re_com.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogoutT.logout("finalPosition"+finalPosition);
//                        LogoutT.logout("哈哈哈");
                        View view = LayoutInflater.from(mContext).inflate(R.layout.input_box,null);
                        //editView自动获取焦点并弹出软键盘
                        final EditText editText = (EditText) view.findViewById(R.id.edit_content);
                        editText.setFocusable(true);
                        final InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0,InputMethodManager.SHOW_FORCED);
                        //获取屏幕高度和宽度
                        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
                        screenHeight = wm.getDefaultDisplay().getHeight();
                        screenWidth = wm.getDefaultDisplay().getWidth();
                        popupWindow = new BasePopupWindow(view, screenWidth, ViewGroup.LayoutParams.WRAP_CONTENT, true, true, true, true);
                        popupWindow.showAtLocation(inflater.inflate(R.layout.frament_main_activity, null), Gravity.BOTTOM,
                                0, 0);
                        Button button = (Button) view.findViewById(R.id.send);
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
//                                ls_content.clear();
//                                okHttpTools.leaveMessage(SharePreferenceTools.getInstance(mContext).getString("name"),editText.getText().toString(),aDatas.get(finalPosition).getId());
                                Message message = new Message(SharePreferenceTools.getInstance(mContext).getString("name"),editText.getText().toString());
                                map.get(finalPosition).add(message);
//                                ls_content.add(message);
                                LogoutT.logout("......3");
                                MyListViewAdapter adapter = new MyListViewAdapter(mContext,map.get(finalPosition),true);
//                                holder.listView.setFocusable(false);
                                holder.listView.setAdapter(adapter);
                                if (imm.isActive()) {
                                    // 如果开启
                                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                                            InputMethodManager.HIDE_NOT_ALWAYS);
                                    // 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
                                }
//                                editText.setFocusable(false);
                                popupWindow.dismiss();
//                                LogoutT.logout("发送");
//                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                });
//                holder.itemView.setTag(position);
                if (mOnItemClickListener != null){
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int pos = holder.getLayoutPosition();
                            mOnItemClickListener.OnItemClick(holder.itemView, pos);
                        }
                    });
                    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            int pos = holder.getLayoutPosition();
                            mOnItemClickListener.onItemLongOnClick(holder.itemView, pos);
                            return false;
                        }
                    });
                }
            }else {
                holder.tv.setText(mDatas.get(position).getProjectName());
                if (mOnItemClickListener != null){
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int pos = holder.getLayoutPosition();
                            mOnItemClickListener.OnItemClick(holder.itemView, pos);
                        }
                    });
                    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            int pos = holder.getLayoutPosition();
                            mOnItemClickListener.onItemLongOnClick(holder.itemView, pos);
                            return false;
                        }
                    });
                }
            }
        }
    }


    //判断底部的位置
    public boolean isFooterView(int position){
        return haveFooterView()&&position==getItemCount()-1;
    }

    private boolean isHeaderView(int position) {
        return haveHeaderView() && position == 0;
    }

    //判断是否有底部
    public boolean haveFooterView(){
        return VIEW_FOOTER != null;
    }

    private boolean haveHeaderView() {
        return VIEW_HEADER != null;
    }

    //判断item的类型
    @Override
    public int getItemViewType(int position) {
        if (isFooterView(position)){
            return TYPE_FOOTER;
        }else if (isHeaderView(position)){
            return TYPE_HEADER;
        }else{
            return TYPE_NORMAL;
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        try {
            if (mRecyclerView == null && mRecyclerView!=recyclerView){
                mRecyclerView = recyclerView;
            }
            ifGridLayoutManager();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public View getLayout(int layoutId){
        return LayoutInflater.from(mContext).inflate(layoutId,null);
    }

    public void addFooterView(View footerView){
        if (haveFooterView()){
            throw new IllegalStateException("footerView has a already exxists!");
        }else{
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            footerView.setLayoutParams(params);
            VIEW_FOOTER = footerView;
            ifGridLayoutManager();
            notifyItemInserted(getItemCount()-1);
        }
    }

    public void addHeaderView(View headerView) {
//        if (haveHeaderView()) {
//            throw new IllegalStateException("hearview has already exists!");
//        } else {
            //避免出现宽度自适应
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            headerView.setLayoutParams(params);
            VIEW_HEADER = headerView;
            ifGridLayoutManager();
            notifyItemInserted(0);
//        }

    }


    //判断是否是GridLayout布局
    private void ifGridLayoutManager(){
        if(mRecyclerView == null) return;
        final RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager){
            GridLayoutManager.SpanSizeLookup originalSpanSizeLookup = ((GridLayoutManager) layoutManager).getSpanSizeLookup();
            ((GridLayoutManager) layoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return (isFooterView(position)) ?
                            ((GridLayoutManager) layoutManager).getSpanCount() :
                            1;
                }
            });

        }
    }


    @Override
    public int getItemCount() {
        int count = 0;
        if (flg== true){
            count = (aDatas == null ? 0 : aDatas.size());
            if (VIEW_FOOTER!=null){
                count++;
            }
            if (VIEW_HEADER!=null){
                count++;
            }
            return count;
        }else {
            count = (mDatas == null ? 0 : mDatas.size());
//            LogoutT.logout(mDatas.size()+"   2222222");
            if (VIEW_FOOTER != null){
                count++;
            }
            if (VIEW_HEADER != null){
                count++;
            }
            return count;
        }
//        int count = (mDatas == null ? 0 : mDatas.size());
//        LogoutT.logout(mDatas.size()+"  2222223333");
//        if (VIEW_FOOTER != null){
//            count++;
//        }
//        if (VIEW_HEADER != null){
//            count++;
//        }
//        return count;
    }

    /**
     * 打开图片浏览器
     * @param position
     * @param url
     */
    public void imageBrower(int position , ArrayList<String> url){
//        Intent intent = new Intent(mContext, ImagePagerActivity.class);
//        intent.putExtra("image_position",position);
//        intent.putExtra("image_url",url);
//        mContext.startActivity(intent);

    }


    public class  MyViewHolder extends RecyclerView.ViewHolder{
        TextView tv;//项目模块中的textView
        ImageView img;//活动模块中的图片
        TextView te_name;//活动模块中的昵称
        TextView content;//活动模块中的内容
        GridView gridView;//活动模块中的图片
//        ImageView img_com;//活动模块中的评论按钮
        ListView listView;//活动模块中的评论列表
        RelativeLayout re_com;//活动模块中的评论按钮
        TextView te_publish_time;//活动模块中的发表时间


        public MyViewHolder(View itemView) {
            super(itemView);
            tv = (TextView) itemView.findViewById(R.id.text_item);
            img = (ImageView) itemView.findViewById(R.id.activity_img_head);
            te_name = (TextView) itemView.findViewById(R.id.activity_te_name);
            content = (TextView) itemView.findViewById(R.id.activity_te_content);
            gridView = (GridView) itemView.findViewById(R.id.gridView);
//            img_com = (ImageView) itemView.findViewById(R.id.commentaries);
            listView = (ListView) itemView.findViewById(R.id.listView);
            re_com = (RelativeLayout) itemView.findViewById(R.id.rela_com);
            te_publish_time = (TextView) itemView.findViewById(R.id.publish_time);
        }
    }

}
